#!/bin/bash

# Baby Tap Server Mobile 构建脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 构建开始时间
BUILD_START_TIME=$(date +%s)

echo -e "${BLUE}🚀 开始构建 Baby Tap Server Mobile 版本...${NC}"

# 检查 gomobile 是否安装
if ! command -v gomobile &> /dev/null; then
    echo -e "${YELLOW}❌ gomobile 未安装，正在安装...${NC}"
    go install golang.org/x/mobile/cmd/gomobile@latest
    gomobile init
    echo -e "${GREEN}✅ gomobile 安装完成${NC}"
fi

# 设置环境变量
export GO111MODULE=on
export CGO_ENABLED=1

# 清理之前的构建
echo -e "${YELLOW}🧹 清理之前的构建...${NC}"
rm -rf ../android/app/src/main/jniLibs/arm64-v8a/libgojni.so
rm -rf ../android/app/src/main/jniLibs/armeabi-v7a/libgojni.so
rm -rf ../android/app/src/main/jniLibs/x86/libgojni.so
rm -rf ../android/app/src/main/jniLibs/x86_64/libgojni.so

# 清理 Go 缓存（可选）
if [ "$1" = "--clean" ]; then
    echo -e "${YELLOW}🧹 清理 Go 缓存...${NC}"
    go clean -cache -modcache -testcache
fi

# 检查依赖
echo -e "${BLUE}📦 检查 Go 依赖...${NC}"
go mod tidy
go get golang.org/x/mobile/bind@latest
go mod download

# 构建 Android AAR
echo -e "${BLUE}📱 构建 Android AAR...${NC}"
AAR_START_TIME=$(date +%s)

gomobile bind -target=android -o ../android/app/libs/babytap-server.aar \
    -androidapi=21 \
    -ldflags="-s -w" \
    -trimpath \
    ./pkg/mobile

AAR_END_TIME=$(date +%s)
AAR_DURATION=$((AAR_END_TIME - AAR_START_TIME))
echo -e "${GREEN}✅ AAR 构建完成 (耗时: ${AAR_DURATION}秒)${NC}"

# 复制 JNI 库文件
echo -e "${BLUE}📦 复制 JNI 库文件...${NC}"
JNI_START_TIME=$(date +%s)

mkdir -p ../android/app/src/main/jniLibs/arm64-v8a
mkdir -p ../android/app/src/main/jniLibs/armeabi-v7a
mkdir -p ../android/app/src/main/jniLibs/x86
mkdir -p ../android/app/src/main/jniLibs/x86_64

# 解压 AAR 并复制 JNI 库
cd ../android/app/libs
unzip -q babytap-server.aar -d temp_aar
cp temp_aar/jni/arm64-v8a/libgojni.so ../src/main/jniLibs/arm64-v8a/
cp temp_aar/jni/armeabi-v7a/libgojni.so ../src/main/jniLibs/armeabi-v7a/
cp temp_aar/jni/x86/libgojni.so ../src/main/jniLibs/x86/
cp temp_aar/jni/x86_64/libgojni.so ../src/main/jniLibs/x86_64/
rm -rf temp_aar
cd ../../../

JNI_END_TIME=$(date +%s)
JNI_DURATION=$((JNI_END_TIME - JNI_START_TIME))
echo -e "${GREEN}✅ JNI 库文件复制完成 (耗时: ${JNI_DURATION}秒)${NC}"

# 计算总构建时间
BUILD_END_TIME=$(date +%s)
TOTAL_DURATION=$((BUILD_END_TIME - BUILD_START_TIME))

echo -e "${GREEN}🎉 构建完成！${NC}"
echo -e "${BLUE}📁 生成的文件：${NC}"
echo -e "  - ../android/app/libs/babytap-server.aar"
echo -e "  - ../android/app/src/main/jniLibs/*/libgojni.so"
echo -e "${BLUE}⏱️  构建统计：${NC}"
echo -e "  - AAR 构建: ${AAR_DURATION}秒"
echo -e "  - JNI 复制: ${JNI_DURATION}秒"
echo -e "  - 总耗时: ${TOTAL_DURATION}秒"

# 检查文件大小
if [ -f "../android/app/libs/babytap-server.aar" ]; then
    AAR_SIZE=$(du -h "../android/app/libs/babytap-server.aar" | cut -f1)
    echo -e "${BLUE}📊 文件大小：${NC}"
    echo -e "  - babytap-server.aar: ${AAR_SIZE}"
fi 